<template>
  <div class="cart">
    <van-sticky>
      <van-nav-bar title="标题" left-text="返回" :right-text="deiting ? '完成' : '编辑'" left-arrow @click-left="$router.go(-1)"
        @click-right="onClickRight" />
    </van-sticky>

    <van-empty description="购物车没有东西了，去购物吧" v-if="!this.cartItems.length" />


    <!-- 购物车列表 -->
    <van-checkbox-group v-model="result" ref="checkboxGroup">
      <div v-for="(item, index) in cartItems" :key="item.cartId" class="">
        <van-swipe-cell>
          <div class="cart-item bfff fl bt1 pt-10 pb-15">
            <van-checkbox :name="item.cartId" class="pl-10"></van-checkbox>
            <div class="fg1">
              <van-card :price="item.price | fMoney" :desc="item.slaveName" :title="item.masterName"
                :thumb="item.imgUrl" style="background-color: white;">
                <template #price>
                  <span class="f16" style="color: #b91717;">￥{{ item.price | fMoney }}</span>
                </template>
                <template #num>
                  <div class="fcc">
                    <van-button class="buttonMinus" size="mini" @click="minus(index, item.cartId)"><van-icon
                        class="mt-8" name="minus" /></van-button>
                    <span class="ml-5 mr-5 f12">x{{ item.buyNum }}</span>
                    <van-button class="buttonMinus" size="mini" @click="add(index, item.cartId)"><van-icon class="mt-8"
                        name="plus" /></van-button>
                  </div>
                </template>
              </van-card>
            </div>
          </div>
          <template #right>
            <van-button square type="danger" text="删除" class="delete-button" @click="butRigDel(item.cartId)" />
          </template>
        </van-swipe-cell>
      </div>
    </van-checkbox-group>

    <!-- 提交订单 -->
    <van-submit-bar :price="totalPrice" :button-text="deiting ? '删除' : '提交订单'" @submit="onSubmit">
      <van-checkbox v-model="checked" @change="onCheckAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import Vue from 'vue';
import { SubmitBar, NavBar, Toast, Stepper, Card, Checkbox, CheckboxGroup, Sticky, Empty, SwipeCell, Dialog } from 'vant';
import request from '../../utils/request'
import { fetchCartAll, fetchCartUpdateNum } from '../../api';

Vue.use(SwipeCell);
Vue.use(Stepper);
Vue.use(Card);
Vue.use(NavBar);
Vue.use(SubmitBar);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Sticky);
Vue.use(Empty);

export default {
  data() {
    return {
      result: [],
      cartItems: [],
      checkedItem: false,
      checked: false,
      deiting: false,
    };
  },
  created() {
    this.carted();
  },
  computed: {
    totalPrice() {
      return this.result.reduce((total, name) => {
        const item = this.cartItems.find(item => item.cartId === name);
        return item ? total + item.price * item.buyNum : total;
      }, 0);
    }
  },
  methods: {
    async carted() {
      const res = await fetchCartAll();
      this.cartItems = res.list;
    },
    minus(index, id) {
      if (this.cartItems[index].buyNum > 1) {
        this.cartItems[index].buyNum--;
        let data = {
          cartId: id,
          buyNum: this.cartItems[index].buyNum
        }
        fetchCartUpdateNum(data);
      } else {
        let delId = [id];
        this.cartDel(delId)
      }
    },
    add(index, id) {
      this.cartItems[index].buyNum++;
      let data = {
          cartId: id,
          buyNum: this.cartItems[index].buyNum
        }
        fetchCartUpdateNum(data);
    },
    async onSubmit() {
      if (this.deiting) {
        this.cartDel(this.result)
      } else {
        if (this.result.length) {
          let data = {
            totalMoney: this.totalPrice,
            cartId: this.result
          }
          request.post('/preOrder/create', data).then(res => {
            this.$router.push({
              path: '/order/submit',
              query: {
                preOrderId: res.result.preOrderId
              }
            })
          })
        } else {
          Toast('请勾选商品');
        }
      }
    },
    onClickRight() {
      this.deiting = !this.deiting;
    },
    onCheckAll() {
      if (this.checked) {
        this.$refs.checkboxGroup.toggleAll(true);
      } else {
        this.$refs.checkboxGroup.toggleAll(false);
      }
    },
    async cartDel(id) {
      try {
        await Dialog.confirm({
          message: '确定删除吗？',
        }).then( async () => {
          let data = {
            cartId: id,
          };
          await request.post('/cart/del', data);
          this.cartItems = this.cartItems.filter((item) => !id.includes(item.cartId));
          this.result = [];
        }).catch(() => {
          console.log('取消删除');
        });

      } catch {
        console.log('取消删除');
      }
    },
    butRigDel(id) {
      let delId = [id];
      this.cartDel(delId)
    }
  }
}
</script>

<style scoped>

.bt1 {
  border-top: 1px solid #f4f4f4;
}

.van-submit-bar {
  bottom: 51px;
}

.buttonMinus {
  /* padding: 6px 5px; */
  height: 20px;
  line-height: 20px;
}

.delete-button {
  height: 100%;
}

.van-image {
  background-color: #f8f8f8;
}
</style>
